import {
	login,
	logout,
	getInfo
} from '@/api/user'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'

import Storage from "@/utils/session"

const useUserStore = {
	state: () => ({
		token: getToken(),
		userInfo: {
			url: "",
			Id: "",
			username: ""
		},
		permissions: [],
		userlist: [], //联系人ID表
		activeItem:{},//用户的请求信息
	}),
	mutations: {
		setactiveItem(state,data){
			state.activeItem=data
		},
		setUserlist(state, data) {
			
			state.userlist = data
		},
		setToken(state, token) {
			state.token = token
			setToken(token)
		},
		setUserInfo(state, data) {
			let userinfo=Object.assign({},state.userInfo )
			let infoData=new Date().getTime();//时间
			state.userInfo = {...userinfo ,...data,infoData}
			Storage.setSession(JSON.stringify({...userinfo ,...data,infoData}))
		},
		setLogOut(state, res) {
			removeToken()
			Storage.removeSession()
			localStorage.clear();
			state.token = ''
			state.userInfo = {
				url: "",
				Id: "",
				username: ""
			}
			state.permissions = []
		}
	},
	actions: {
		// 登录
		actionLogin(context, userInfo) {
			const username = userInfo.username.trim()
			const password = userInfo.password.trim()
			return new Promise((resolve, reject) => {
				login(username, password).then(res => {
					context.commit("setUserInfo", res.data)
					context.commit("setToken", res.token)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		//验证token是否有效
		actionToken(context) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取并更新用户信息
		actionGetInfo(context, data) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					context.commit("setUserInfo", res.data)
					context.commit("setToken", res.token)
					resolve(res.data)
				}).catch(error => {
					reject(error)
				})
			})
		},
		
		// 退出系统 需配合后端
		actionLogOut(context) {
			return new Promise((resolve, reject) => {
				logout().then((data) => {
					context.commit("setLogOut")
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}


export default useUserStore